"""报告查询服务"""

import logging
from typing import List, Optional, Dict, Any

from ..schemas import ReportMainQueryRequest, ReportInfo, ErrorResponse
from ..services import generate_mock_reports
from ..core.error_codes import ErrorCode
from ..core.exceptions import ParameterException, NotFoundException


logger = logging.getLogger(__name__)


class ReportService:
    """报告查询服务类"""

    @staticmethod
    def validate_query_request(request: ReportMainQueryRequest) -> None:
        """验证查询请求参数"""
        # 验证必填参数
        if not request.medical_card_number:
            raise ParameterException("就诊卡号不能为空")

        if not request.id_card:
            raise ParameterException("身份证号不能为空")

        if not request.patient_name:
            raise ParameterException("就诊人姓名不能为空")

        if not request.start_time:
            raise ParameterException("开始时间不能为空")

        if not request.end_time:
            raise ParameterException("结束时间不能为空")

        # 验证时间范围
        from datetime import datetime
        start_dt = datetime.strptime(request.start_time, "%Y-%m-%d %H:%M:%S")
        end_dt = datetime.strptime(request.end_time, "%Y-%m-%d %H:%M:%S")

        if start_dt >= end_dt:
            raise ParameterException("开始时间必须早于结束时间")

        # 验证时间范围不能超过1年
        if (end_dt - start_dt).days > 365:
            raise ParameterException("查询时间范围不能超过1年")

        # 验证医院ID格式
        if request.hospital_id:
            hospital_ids = [hid.strip() for hid in request.hospital_id.split(",")]
            for hid in hospital_ids:
                if not hid or len(hid) > 10:
                    raise ParameterException(f"医院ID格式错误: {hid}")

    @staticmethod
    def parse_hospital_ids(hospital_id_str: Optional[str]) -> Optional[List[str]]:
        """解析医院ID字符串"""
        if not hospital_id_str:
            return None

        hospital_ids = [hid.strip() for hid in hospital_id_str.split(",")]
        return [hid for hid in hospital_ids if hid]  # 过滤空字符串

    @staticmethod
    def query_reports(request: ReportMainQueryRequest) -> Dict[str, Any]:
        """查询报告主信息"""
        try:
            # 验证请求参数
            ReportService.validate_query_request(request)

            # 解析医院ID
            hospital_ids = ReportService.parse_hospital_ids(request.hospital_id)

            logger.info(f"查询报告信息 - 患者: {request.patient_name}, "
                       f"就诊卡: {request.medical_card_number}, "
                       f"时间范围: {request.start_time} - {request.end_time}")

            # 生成模拟数据（实际项目中这里应该查询数据库）
            reports = generate_mock_reports(
                patient_name=request.patient_name,
                start_time=request.start_time,
                end_time=request.end_time,
                hospital_ids=hospital_ids,
                patient_type=request.patient_type,
                count=10  # 默认生成10条记录
            )

            # 如果没有找到数据，返回特定的错误码
            if not reports:
                logger.info(f"未找到患者 {request.patient_name} 的报告数据")
                return {
                    "success": True,
                    "msg": "未查询到数据",
                    "code": ErrorCode.NO_DATA,
                    "data": {
                        "patient_name": request.patient_name,
                        "report": []
                    }
                }

            # 构建响应数据
            response_data = {
                "patient_name": request.patient_name,
                "report": [report.dict() for report in reports]
            }

            logger.info(f"查询成功 - 找到 {len(reports)} 条报告记录")

            return {
                "success": True,
                "msg": "成功",
                "code": ErrorCode.SUCCESS,
                "data": response_data
            }

        except ParameterException as e:
            logger.error(f"参数验证失败: {e.message}")
            return {
                "success": False,
                "msg": e.message,
                "code": e.code,
                "data": e.data
            }
        except Exception as e:
            logger.error(f"查询报告失败: {str(e)}", exc_info=True)
            return {
                "success": False,
                "msg": "系统错误",
                "code": ErrorCode.SYSTEM_ERROR,
                "data": None
            }

    @staticmethod
    def get_report_detail(report_id: str) -> Optional[Dict[str, Any]]:
        """获取报告详情"""
        # 这里可以实现报告详情查询逻辑
        # 目前返回模拟数据
        logger.info(f"查询报告详情 - 报告ID: {report_id}")

        # 模拟报告详情数据
        report_detail = {
            "report_id": report_id,
            "patient_name": "张之路",
            "patient_age": 45,
            "patient_gender": "男",
            "hospital_name": "山东省立医院",
            "department": "内科",
            "doctor": "王春霞",
            "report_time": "2018-02-01 18:20:20",
            "report_type": "检验报告",
            "item": "血常规",
            "results": [
                {
                    "item_name": "白细胞计数",
                    "result": "6.5",
                    "unit": "×10^9/L",
                    "reference_range": "4.0-10.0",
                    "status": "正常"
                },
                {
                    "item_name": "红细胞计数",
                    "result": "4.2",
                    "unit": "×10^12/L",
                    "reference_range": "3.5-5.5",
                    "status": "正常"
                }
            ],
            "conclusion": "血常规检查结果基本正常",
            "status": "已审核"
        }

        return report_detail

    @staticmethod
    def get_report_statistics(patient_id: str, start_time: str, end_time: str) -> Dict[str, Any]:
        """获取报告统计信息"""
        # 这里可以实现报告统计逻辑
        logger.info(f"查询报告统计 - 患者: {patient_id}, 时间: {start_time} - {end_time}")

        # 模拟统计数据
        statistics = {
            "total_reports": 15,
            "laboratory_reports": 10,
            "examination_reports": 5,
            "recent_report_time": "2018-02-01 18:20:20",
            "abnormal_reports": 2,
            "pending_reports": 1
        }

        return statistics